package com.yyl.rbacs.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yyl.rbacs.annotation.DataFilter;
import com.yyl.rbacs.sys.entity.SysDept;
import com.yyl.rbacs.sys.entity.SysUser;
import com.yyl.rbacs.sys.mapper.SysUserMapper;
import com.yyl.rbacs.sys.service.ISysDeptService;
import com.yyl.rbacs.sys.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yyl.rbacs.utils.Constants;
import com.yyl.rbacs.utils.PageQueryUtil;
import com.yyl.rbacs.utils.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author YuanSir
 * @since 2022-10-28
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    
    @Autowired
    ISysDeptService deptService;
    
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    @DataFilter
    public PageVo<SysUser> queryUserByPage(Map<String, String> params) {
        
        String username = params.get("username"); // 页面输入的用户名查询条件
    
        String sql = params.get(Constants.DATA_FILTER);
    
        //分页工具类创建分页对象
        Page<SysUser> sysUserPage = PageQueryUtil.getPage(params);
    
        // 只查询没有被禁用的用户，并设置查询条件，并拼接where条件
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getStatus, 1)
                .eq(StringUtils.isNotBlank(username), SysUser::getUsername, username)
                .apply(StringUtils.isNotBlank(sql), sql);
    
        page(sysUserPage, sysUserLambdaQueryWrapper);
        
        //把所有的user对象中的deptName进行赋值
        List<SysDept> deptList = deptService.list();
        
        //List<SysDept> ——> Map<部门id，部门名称>
        HashMap<Long, String> deptMap = new HashMap<>();
        
        deptList.forEach(dept -> deptMap.put(dept.getDeptId(), dept.getName()));
        
        //遍历sysUserPage进行部门名称的赋值操作
        sysUserPage.getRecords().forEach(user -> user.setDeptName(deptMap.get(user.getDeptId())));
    
        return new PageVo<>(sysUserPage);
        
    }
}
